package com.atguigu.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.feign.MemberFeignService;
import com.atguigu.gulimall.ware.to.MemberReceiveAddressTo;
import com.atguigu.gulimall.ware.vo.FareVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.WareInfoDao;
import com.atguigu.gulimall.ware.entity.WareInfoEntity;
import com.atguigu.gulimall.ware.service.WareInfoService;

import javax.annotation.Resource;


@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {

    @Resource
    MemberFeignService memberFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        LambdaQueryWrapper<WareInfoEntity> wrapper = new LambdaQueryWrapper<>();
        String key = (String)params.get("key");
        if(StringUtils.isNotBlank(key)){
            wrapper.and(w->{
                w.eq(WareInfoEntity::getId,key)
                        .or().like(WareInfoEntity::getName,key)
                        .or().like(WareInfoEntity::getAreacode,key)
                        .or().like(WareInfoEntity::getAddress,key);
            });
        }
        IPage<WareInfoEntity> page1 = new Query<WareInfoEntity>().getPage(params);
        System.err.println(page1.getTotal());
        System.err.println(page1.getCurrent());
        System.err.println(page1.getSize());
        System.err.println(page1.getPages());
        IPage<WareInfoEntity> page = this.page(
                page1,
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        return pageUtils;
    }

    @Override
    public FareVo getFare(Long addrId) {
        R info = memberFeignService.info(addrId);
        MemberReceiveAddressTo address = info.getData("memberReceiveAddress", new TypeReference<MemberReceiveAddressTo>() {
        });
        if(address!=null){
            FareVo vo = new FareVo();
            String phone = address.getPhone();
            String substring = phone.substring(phone.length() - 1, phone.length());
            vo.setFare(new BigDecimal(substring));
            vo.setMemberReceiveAddressTo(address);
            return vo;
        }
        return null;
    }

}